package com.sd365.permission.centre.service.util;

import com.alibaba.fastjson.JSON;
import com.sd365.common.core.mq.ActionType;
import com.sd365.common.core.mq.MqDataSyncMsg;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Component
public class SendMQMessageUtil {
    public static String EXCHANGE_NAME = "centreToOmp_EXEC";
    private RabbitTemplate rabbitTemplate;
    private static final String ROUTE_KEY = "centreToOmp";

    //构造方法注入
    @Autowired
    public SendMQMessageUtil(RabbitTemplate rabbitTemplate, MQCallbackUtil mqCallbackUtil) {
        this.rabbitTemplate = rabbitTemplate;
        //这是是设置回调能收到发送到响应
        rabbitTemplate.setConfirmCallback(mqCallbackUtil);
        //如果设置备份队列则不起作用
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnCallback(mqCallbackUtil);
    }

    /**
     * 获取最新的数据库信息并封装到MqDataSyncMsg中转换成json字符串->发送 单个datalist
     *
     * @param actionType
     * @return
     * @throws IOException
     */
    public void SendMessage(ActionType actionType, String exchangeName, String tableName, Object... objects) {
        List<Object> currentList = new ArrayList<>();
        for (Object data : objects) {
            currentList.add(data);
        }
        MqDataSyncMsg mqDataSyncMsg = new MqDataSyncMsg(tableName, actionType, currentList);
        String message = JSON.toJSONString(mqDataSyncMsg);
        rabbitTemplate.convertAndSend(exchangeName, ROUTE_KEY, message);
    }

    /**
     * 广播模式,谁关联这个交换机谁就可以获取这个消息，如果有队列关联这个但是不消费这条消息就会造成消息的堆积
     *
     * @param actionType
     * @return
     * @throws IOException
     */
    public void fanoutSendMessage(ActionType actionType, String exchangeName, String tableName, Object... objects) {
        List<Object> currentList = new ArrayList<>();
        for (Object data : objects) {
            currentList.add(data);
        }
        MqDataSyncMsg mqDataSyncMsg = new MqDataSyncMsg(tableName, actionType, currentList);
        String message = JSON.toJSONString(mqDataSyncMsg);
        rabbitTemplate.convertAndSend("easy2pass_fanout_exchange", "", message);

    }
}
